<template>
<div class="app-container" >

    <el-row >
    <el-col :span="24"   >
      <el-button size="mini"  type="primary" @click="addRole">添加</el-button>

      <el-table
      @click="changeBox"
      @check="getRoleCheckedNodes"
      ref="singleTable"  
      highlight-current-row
      @current-change="handleCurrentChange"
      :data="roles"
      border
      style="width: 100%">
      <el-table-column
      property="id"
        label="ID">

      </el-table-column>
      <el-table-column
      property="name"
        label="名称"
        >
      </el-table-column>
      <el-table-column
      property="remark"
        label="备注">
      </el-table-column>
      <el-table-column
      property="handle"
        label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="danger" @click="delRole(scope.row.id)">删除</el-button>
          <el-button size="mini" type="info" @click="editRole(scope.row.id)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table> 


  <edit-role-dialog @refresh="refresh" ref="editDialog"></edit-role-dialog>
  <add-role-dialog @refresh="refresh" ref="addDialog"></add-role-dialog>
  </el-col>
  </el-row>
  <div>
    <el-divider content-position="left"><h3 >角色菜单授权</h3></el-divider>

      <el-row>
        <el-col :span="24">
          <!-- @change="checkedTree"   -->
              <!-- v-model="vCheckedTree" -->
            <el-tree
              ref="tree"
              :data="data"
              :show-checkbox=flag
              :default-checked-keys="defaultList"
   
              @check="getCheckedNodes"
              @check-change="caseCheckChange"
              highlight-current
              

              node-key="id"
              :props="{checkStrictly: true}"
              :expand-on-click-node="false">
              <!-- disabled:'hidden', -->
               <!-- <div class="grid-content bg-purple-dark"> -->
            <el-col class="custom-tree-node" slot-scope="{data }">
              <el-col :span="4">
                    {{data.name}}
                    
                </el-col> 
                <el-col :span="4" offset="">
                  
                    <el-tag type="success" v-if="data.component=='目录'">
                      {{data.component}}
                    </el-tag>

                    <el-tag type="danger" v-if="data.component=='菜单'">
                      {{data.component}}
                    </el-tag>

                    <el-tag type="warning" v-if="data.component=='按钮'">
                      {{data.component}}
                    </el-tag>

                    <span type="success" v-if="data.component==''">

                    </span>
                  
                </el-col>
                <el-col :span="4">
                  <span v-if="data.meta.icon=''"> </span>
                 <i :class="data.meta.icon"></i>
                </el-col>
              <el-col :span="4">
                {{data.top}}
                
              </el-col>
                <el-col :span="4">{{data.path}}</el-col>
              </el-col>

            </el-tree>     

        </el-col>
        <div></div>

         <div>
         </div>

      </el-row>
      <el-row  >
          <el-col :span="24" >
            <el-col :span="4">
                <el-checkbox :disabled=!flag @change="checkedAll"  v-model="checked">全选</el-checkbox> 
            </el-col>
            <el-col :span="2" :offset="12">
            <!-- <template slot-scope="scope2"> -->
              <el-button size="mini" :disabled=!flag type="danger" @click="resetChecked">重置</el-button>
                <el-button size="mini" :disabled=!flag type="success" @click="commitChecked">提交</el-button>
            <!-- </template> -->
                
            </el-col >
            
            <el-col :span="20">
              
            </el-col>
           
          </el-col>
          
        </el-row>

  </div>
  

</div>
</template>

<script>
import http from '@/utils/request.js'

import EditRoleDialog from './EditRoleDialog.vue'
import AddRoleDialog from './AddRoleDialog.vue'

export default {
  components:{
        
    EditRoleDialog,
    AddRoleDialog

      },
  data() {
    return {
          valId:0,
          checked:false,
          flag: false,
          flash_flag:'true',
          roles: [],
          data:[],
          roleTableData:[],
          defaultList:[],
          saveList: [],
          testList:[1,2,3],
          roleDto:{},
          list:[],
          // alldatalen:this.alllen
      
    
    }
  },
  mounted(){

    this.initMenuData();
    this.showRoleData();
    this.showMenuData();
    // console.log("this.$refs.tree.getCheckedKeys()----->",this.$refs.tree.getCheckedKeys());

      
      
    
  },
  methods:{
    initRoleData(){
      http.get(`role`).then((res)=>{
           console.log("role的res数据：------------",res)
          this.roles = res
          
        })


    },

    initMenuData(){

      const flag_name = 'true'
      const id = 1
      console.log("flag_name---->",flag_name);
      http.get(`role/get/${flag_name}`).then((res)=>{
          
          this.list = this.convertTreeData(res)
          localStorage.setItem('dataslen',this.list.length)
       
           caseCheckChange(this.list.length)
           this.refresh();
         
      
      })

    },

    showRoleData(){

      console.log("show方法")
        http.get(`role`).then((res)=>{
           console.log("role的res数据：------------",res)
          this.roles = res
          
        })
        
      
      },
      async showMenuData(flag){
        this.flag = flag
        console.log("flag--->",this.flag);
         const flag_name = 'true'
         const id = 1
      console.log("flag_name---->",flag_name);
      await http.get(`role/get/${flag_name}`).then((res)=>{
          // console.log("role-flag的res数据：------------",this.$refs.tree.getCheckedNodes(res))
          console.log("树形res：",res)
          this.data = res
          //注意这行
          // this.list = this.convertTreeData(res)

          this.list = this.convertTreeData(this.res)
          
          console.log("树形数组转换后：",this.list.length)


          localStorage.setItem('dataslen',this.list.length)
           this.alldatalen = this.list.length
           caseCheckChange(this.list.length)

          
          console.log("tree树形多选--->this.",this.alldatalen);
          
      
      })

      },
      changeBox(){
       
        // getRoleCheckedNodes
        // this.$refs.singleTable.setCurrentRow(row.id);
        // this.valId = this.$refs.singleTable.getCheckedNodes(this.singleTable);
        
        console.log("changeBox------->",this.valId);
        this.flag = true
        this.valId = this.id
        if(flash_flag === 'true'){
          this.showMenuData();
        }
        else{}
        
      },
      addRole(){
        this.$refs.addDialog.addRoleDialogVisible = true

      },
      editRole(id){

      console.log("edit---------->id",id);
      this.$refs.editDialog.getById(id);
      // 让编辑模态框展示
      this.$refs.editDialog.editRoleDialogVisible = true


      },
      async delRole(id){
      // this.$refs.delDialog.delDeptDialogVisible = true
      console.log("id的值-------------------》》",id);
      try {
        // 对于this.confirm() 使用 await等待的时候，用户点击取消，是通过抛异常的方式
        await this.$confirm("你确定要删除这条数据吗?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          closeOnClickModal: false,
          type: "success",
        });
        // 代码如果能够走下来表示用户点击了确认按钮
        // 删除用户
        await http.delete(`role/${id}`);
        this.$message({ message: "删除成功", type: "success", duration: 1000 });
        this.refresh();
      } catch (err) {
        // 代码如果进入了 catch块，表示用户点击了取消按钮
        console.log(err);
      }
      this.showDept();
      
    },
    setCurrent(row) {
        this.$refs.singleTable.setCurrentRow(row.id);

        console.log("row.id____>",row.id,row);
      },
      handleCurrentChange(val) {
        
        this.flag = true
        
        console.log("handle-row.id____>",val.id);
        
        this.showMenuByRole(val.id)
        
        this.currentRow = val;
         
        // this.valId = this.val.id
        
      },
      //回显数据多选框
      showMenuByRole(id){
        this.valId = id
        http.get(`role/menu/${id}`).then((res)=>{
          console.log("role-menu-by-role的res数据：------------",res,id)
          
          // this.data = res
          this.defaultList = []
          res.forEach(element => {
            this.defaultList.push(element.id)
            
          });
          // this.defaultList = this.res 
          
        this.$nextTick(() => {
          console.log("this.defaultList2---->",this.defaultList);
          this.$refs.tree.setCheckedKeys(this.defaultList) 
          
         
        })
       
        })

      },
     
       caseCheckChange(alllen){
        // console.log("data多选------------->>>",this.convertTreeData(this.$refs.tree.getCheckedNodes(this.data)));

        console.log("树形tree多选------------->>>",this.$refs.tree.getCheckedNodes(this.tree).length,localStorage.getItem('dataslen'),this.checked);
        
        // 
        if(this.$refs.tree.getCheckedNodes(this.tree).length != localStorage.getItem('dataslen') && this.checked==true){

          if(this.$refs.tree.getCheckedNodes(this.tree).length==0){
            this.checked==false
          }
          this.checked = false
          //1.全选为true 2.data填充 3.触发change事件 4.判断是否
        }
        // localStorage.getItem('dataslen')
        else if(this.$refs.tree.getCheckedNodes(this.tree).length == localStorage.getItem('dataslen') && this.checked==false)
        {this.checked = true}


      },
      convertTreeData(data) {
        for (let i = 0; i < data.length; i++) {
            if (data[i].children != undefined) {
                const temp = data[i].children
                delete data[i].children
                data = data.concat(temp)
            }
        }
        return data
      },
      async checkedAll(){

          // console.log("进入全选...");
          //   //全选
          //   this.$refs.tree.setCheckedNodes(this.data);

        console.log("多选是否被选中：",this.checked);
        if (this.checked) {
          console.log("进入全选...",this.checked);

          if(this.$refs.tree.getCheckedNodes(this.tree).length == this.alldatalen){

            

              this.checked = true
          }

          console.log("this.data.length长度：",this.$refs.tree.getCheckedNodes);



          console.log("this.$refs.tree.vCheckedTree:",this.$refs.tree.vCheckedTree);


          
            //全选
          await  this.$refs.tree.setCheckedNodes(this.data);
            console.log("xxx-data全选数据为：",this.data);
        }else{
          console.log("进入取消选中...");
            //取消选中
            this.$refs.tree.setCheckedKeys([]);
        }

      },
      resetChecked(){
        this.saveList = this.defaultList
        this.$refs.tree.setCheckedKeys(this.saveList) 

      },
      commitChecked(){
        this.testList = []
        // -------------------这个node的类型不对，改一下！！！！！
        this.testList = this.$refs.tree.getCheckedNodes(this.tree)
        console.log("this.roleDto.id:----->",this.valId);
        this.roleDto = {id:this.valId,ids:this.testList}
        console.log("this.roleDto:----->",this.roleDto);
        // ids:遍历现在被选中的多选框，得到一个数组，传过去
        http.post(`role/delAndinsert`,this.roleDto).then((res)=>{
          console.log("role-menu-by-role2的res数据：------------",res,this.valId,this.saveList)
          // this.data = res
          
       
        })
        // this.flash_flag = 'false'
        // this.checkBox();
        // this.showRoleData()

        // this.initMenuData()
        // this.flag = false

        
        // this.checked = false
        // this.refresh()
        //到底为啥不是角色（上）有显示，要么就是菜单出来多选框
        // this.showRoleData()
        // this.flag = false
        // console.log("this.$refs.tree.getCheckedNodes(this.tree)",this.$refs.tree.getCheckedNodes(this.tree));
        this.$message({ message: "提交成功", type: "success", duration: 1000 });
        // this.showRoleData();
        this.showMenuData();
        this.flag = false
        // this.initMenuData();
        // this.flag = false
        // this.showMenuData(flag)
        // this.checked = false
        // this.refresh()
        // this.resetChecked()
  
        
        

      },
      refresh(){
        this.showRoleData();
        this.showMenuData();
        // this.flag = false

      }
  }
}
</script>

<style>

</style>
